package com.cctc.security.webservices.impl;

import java.sql.CallableStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.TimeZone;

import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.CallableStatementCallback;
import org.springframework.stereotype.Component;

import com.cctc.framework.util.MD5Util;
import com.cctc.security.dao.WebServicesUserDao;
import com.cctc.security.webservices.AcessToken;

@Component("acessTokenImpl")
@SOAPBinding(style = Style.RPC)
@WebService(serviceName = "AcessTokenService", targetNamespace = "http://www.cctc.com/fw", endpointInterface = "com.cctc.security.webservices.AcessToken")
public class AcessTokenImpl implements AcessToken
{
    @Autowired
    private WebServicesUserDao webServicesUserDao;
    
    private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
    
    
    @Override
    public String getAcessToken(final String userName, final String password)
    {
        Date d = new Date();
        df.setTimeZone(TimeZone.getTimeZone("UTC"));
        
        String result = (String) webServicesUserDao.getJdbcTemplate().execute("{call check_WEBSERVICE_USER(?,?,?)}",
                new CallableStatementCallback<Object>()
                {
                    @Override
                    public Object doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException
                    {
                        cs.setString(1, userName);
                        cs.setString(2, password);
                        cs.execute();
                        //System.out.println(cs.getString(3));
                        return cs.getString(3);
                    }
                    
                });
        
        StringBuilder sb=new StringBuilder();
        sb.append(userName).append(df.format(d)).append(password).append(AcessTokenImpl.getRandom(new Random().nextInt())).append(result);
        return MD5Util.md5s(sb.toString().getBytes()).toUpperCase();
    }
    
    public static  String  getRandom(int i)
    {
        if(i>99)
        {
            return ""+i;
        }else if(i>9){
            return "0"+i;
        }else{
            return "00"+i;
        }
    }
    public static void main(String[] args)
    {
        System.out.println(new Random().nextInt(1000));
        //Date d = new Date();
        //SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        //System.out.println(df.format(d));
        //df.setTimeZone(TimeZone.getTimeZone("UTC"));
        //System.out.println(df.format(d));
    }
}
